package m202406.d29;

import java.util.Stack;

/**
 * @@author: 爱做梦的锤子
 * @date: 2024/6/29 17:16
 */
public class Q402 {

    public static void main(String[] args) {
        Q402 q402 = new Q402();
        q402.removeKdigits("1001", 1);
    }

    public String removeKdigits(String num, int k) {
        if (k >= num.length()) {
            return "0";
        }
        Stack<Character> stack = new Stack<>();
        int counter = 0;
        int i = 0;
        for (; i < num.length() && counter < k; i++) {
            if (stack.isEmpty() || stack.peek() <= num.charAt(i)) {
                stack.push(num.charAt(i));
                continue;
            }
            while (!stack.isEmpty() && counter < k && stack.peek() > num.charAt(i)) {
                stack.pop();
                counter++;
            }
            stack.push(num.charAt(i));
        }
        if (counter < k) {
            for (int j = 0; j < k - counter; j++) {
                stack.pop();
            }
        }
        StringBuilder sb = new StringBuilder();
        for (Character c : stack) {
            sb.append(c);
        }
        sb.append(num.substring(i));
        while (!sb.isEmpty() && sb.charAt(0) == '0') {
            sb.delete(0, 1);
        }
        return sb.isEmpty() ? "0" : sb.toString();
    }
}
